package com.pearlsoft.rms.vcenter;

import java.util.logging.Level;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Service;

import com.pearlsoft.rms.VmConstants;
import com.vmware.vcloud.sdk.VCloudException;
import com.vmware.vcloud.sdk.VcloudClient;

/**
 * 
 * @author rainshow
 * @Created 2012-5-17 下午05:59:33
 */

@Service("vcloudConnectionManager")
@Scope("singleton")
public class VcloudConnectionManagerImpl implements VcloudConnectionManager {
    private static Log logger = LogFactory.getLog(VcloudConnectionManagerImpl.class);
    private VcloudConnection connection;
    private long lastVisited = -1;
    private long timeout = 15 * 60 * 1000;

    @Override
    public VcloudConnection getConnection() throws VCloudException {
        synchronized (VcloudConnectionManagerImpl.class) {
            if (System.currentTimeMillis() - lastVisited > timeout) {
                if (connection != null) {
                    logger.info("VCLOUD连接超时，重新连接。");
                } else {
                    VcloudClient.setLogLevel(Level.OFF);
                }
                this.connection = new VcloudConnection(VmConstants.CLOUD_URL, VmConstants.CLOUD_USERNAME,
                        VmConstants.CLOUD_PASSWORD);
                connection.connect();
            }
            this.lastVisited = System.currentTimeMillis();
        }
        return connection;
    }

}
